package connection;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


import org.apache.log4j.FileAppender;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.eclipse.core.runtime.IProgressMonitor;

import common.BodySet;
import common.DiscussionSentence;
import easytalk.connectivity.ILogWriter;

public abstract class AbstarctServerConnection implements IServerConnection {

	protected ServerConnectionConfig config = new ServerConnectionConfig();
	protected ILogWriter logWriter = new ILogWriter() {

		@Override
		public void write(String text) {
			for (IProgressMonitor monitor : progressListener) {
				monitor.setTaskName(text);
			}
			
		}

		@Override
		public void write(String text, int progress) {
			for (IProgressMonitor monitor : progressListener) {
				monitor.setTaskName(text);
				monitor.worked(progress);
			}
			
		}
		
	};
	protected Logger logger;
	private List<IProgressMonitor> progressListener = new ArrayList<IProgressMonitor>();
	
	public AbstarctServerConnection() {
		logger = Logger.getLogger(getClass());
		try {
			FileAppender appender = new FileAppender(new PatternLayout(),logger.getName() + ".log");
			logger.addAppender(appender);
		
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	
	public ServerConnectionConfig getConfig() {
		return config;
	}

	public void setConfig(ServerConnectionConfig config) {
		this.config = config;
	}

	public abstract void hookBodySet(BodySet bSet) throws Exception;

	public abstract boolean login(String username, String password)
			throws Exception;

	public abstract void logout();

	public abstract String getName();
	
	
	
	@Override
	public void addProgressListener(IProgressMonitor monitor) {
		progressListener.add(monitor);
		
	}
	
	@Override
	public void removeProgressListeners() {
		progressListener = new ArrayList<IProgressMonitor>();
	}


	@Override
	public void sendMessage(String id, DiscussionSentence sentence) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void sendFastMessage(String id, String toBeSent) {
		throw new UnsupportedOperationException();
		
	}

	@Override
	public boolean equals(Object obj) {
		if (obj instanceof AbstarctServerConnection) {
			return ((AbstarctServerConnection) obj).getConfig().equals(config);
		}
		return false;
	}

}
